package com.example.managerment.filter;


import com.example.managerment.module.vo.ResultVO;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码的过滤器
 */
@Component//注入到Spring容器中
public class VerificationCodeFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        /**
         * 强转为 ServletRequest和ServletResponse的子接口：
         *      HttpServletRequest和HttpServletResponse
         */
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;


        //如果是post请求，并且路径是 login 再进行校验，否则放行
        if ("POST".equals(req.getMethod()) && "/login".equals(req.getServletPath())) {
            System.out.println("VerificationCodeFilter-VERIFY_CODE = " + req.getSession().getAttribute("VERIFY_CODE"));
            //获取 session 中的验证码字符串
            String verifyCode = (String) req.getSession().getAttribute("VERIFY_CODE");
            //获取客户端传递过来的验证码
            String vc = req.getParameter("verifyCode");
            /**
             * 如果 客户端传递过来的验证码
             *   为"" 为 null 和session的值不一致 视为 验证码错误
             */
            if (vc == null ||"".equals(vc) ||  !vc.toLowerCase().equals(verifyCode.toLowerCase())) {
                //设置响应头 要不然会出现乱码情况
                resp.setHeader("Content-Type", "text/html;charset=utf-8");

                //要往前端返回的数据/抛出异常
                ResultVO resultVO = new ResultVO("验证码有误");
                resultVO.out(resp);
            } else {//验证码正确
                //让过滤器往下执行
                chain.doFilter(request, response);
            }
        } else {
            //让过滤器往下执行
            chain.doFilter(request, response);
        }
    }
}